import gitlab
import re
from apps.extention.settings import config


class GitlabClient:
    __git_pattern = r"^(http|git)[\s\S].+\/([\w\-_]+)\.git"

    def __init__(self, url):
        if url is None and url == '':
            raise ValueError('url不能为空！')
        self.git_url = url
        self.client = gitlab.Gitlab(config.GITLAB_URL, private_token=config.GITLAB_TOKEN)

    def get_project_list(self):
        self.client.projects.list(all=True)

    def get_project(self):
        key_matcher = re.search(self.__git_pattern, self.git_url)
        if key_matcher.group(2):
            search_keyword = key_matcher.group(2)
            project_list = self.client.projects.list(search=search_keyword)
            if key_matcher.group(1) == 'git':
                for item in project_list:
                    if item.ssh_url_to_repo == self.git_url:
                        return {'id': item.id, 'description': item.description, 'status': 0}

            if key_matcher.group(1) == 'http':
                for item in project_list:
                    if item.http_url_to_repo == self.git_url:
                        return {'id': item.id, 'description': item.description, 'status': 0}
        return {'status': 1, 'msg': '获取git project 出错了！'}

    def get_project_module(self, project_id):
        if not project_id:
            return {'status': 1, 'msg': 'project id 不能为空！'}

        project_info = self.client.projects.get(project_id)
        root_module = [x['name'] for x in project_info.repository_tree() if x['type'] == 'tree' and x['name'] != 'sql']
        for index in range(len(root_module)):  # src直接返回
            if root_module[index] == 'src':
                return root_module

        for index in range(len(root_module)):
            package_path = [y for y in project_info.repository_tree(path=root_module[index])
                            if y['path'] == root_module[index] + '/src']
            if len(package_path):
                continue
            child_module = [x['path'] for x in project_info.repository_tree(path=root_module[index])
                            if x['type'] == 'tree']
            root_module.extend(child_module)

        return root_module

    def get_project_branch(self, project_id):
        if not project_id:
            return {'status': 1, 'msg': 'project id 不能为空！'}
        project_info = self.client.projects.get(project_id)
        if project_info:
            return [x.name for x in project_info.branches.list()]
        else:
            return {'status': 1, 'msg': 'project branch 为空！'}

    def update_project_setting(self, project_id, jenkins_url='', token=''):
        project_info = self.client.projects.get(project_id)
        return project_info.hooks.list()
